package com.usian.comment.service.Impl;

import com.usian.comment.feign.ApUserFeign;
import com.usian.comment.service.ApCommentService;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojo.ApComment;
import com.usian.model.comment.pojo.ApCommentLike;
import com.usian.model.comment.pojo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private ApUserFeign apUserFeign;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //远程调用获取作者名称
        ApUser apUser = apUserFeign.findUserById(user.getId());


        //monngo中保存评论内容
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId()); //entryId文章id
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {

        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //校验评论是否存在
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(apComment!=null){

            if(dto.getOperation()==0){
                //点赞  update apcomment like    insert apcommentlike
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);

                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(apComment.getId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
            }else if(dto.getOperation()==1){
                //取消点赞    update apcomment like-1    delete apcommentlike
                apComment.setLikes(apComment.getLikes()<=0 ? 0:apComment.getLikes()-1);
                mongoTemplate.save(apComment);

                Query query=new Query().addCriteria(Criteria.where("authorId").is(user.getId())
                        .and("commentId").is(dto.getCommentId()));
                mongoTemplate.remove(query,ApCommentLike.class);
            }
        }

        //返回点赞数量
        Map<String,Object> result = new HashMap<>();
        result.put("likes",apComment.getLikes());
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {

        //1：校验参数
        if(dto==null ||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //2:根据文章id 查询评论列表
        Query query =new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()))
                .limit(10).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);


        //3:如登录  用户查询过滤点赞哪些评论 点赞
        //获取登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.okResult(apCommentList);
        }

        //select * from apcommentlike  where commentId in( select id from apcomment )
        List<String> apCommentIdList = apCommentList.stream().map(a -> a.getId()).collect(Collectors.toList());
        Query query1 =new Query();
        query1.addCriteria(Criteria.where("commentId").in(apCommentIdList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikeList = mongoTemplate.find(query1, ApCommentLike.class);

        List<ApCommentVo> resultList = new ArrayList<>();

        apCommentList.stream().forEach(x ->{
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(x,apCommentVo);
            for(ApCommentLike like:apCommentLikeList){
                if(x.getId().equals(like.getCommentId())){
                    apCommentVo.setOperation((short) 0);
                    break;
                }
            }
            resultList.add(apCommentVo);
        });

        return ResponseResult.okResult(resultList);
    }
}
